<?php
/**
 *收货模块
 * @author chamlinsun@qq.com
 */
defined('SYSPATH') or die ('No direct access allowed.');

class Controller_receipt extends Template{
    protected $user; //用户ID
    protected $recieve_man; //用户名
    protected $url;

    /**
     *收货单操作
     */
    public function before(){
        $userid = User::active_user()->id;
        $this->user = $userid;
        $username = ORM::factory('user')
            ->where('id','=',$userid)
            ->find();
        $this->recieve_man = $username->name;
        try{
            ACL::Required('receipt_update');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        parent::before();
    }

    //显示收货界面
    public function Action_index(){
        $this->title = '扫描收货';

        $this->response->body(View::factory('receipt/receipt'));
    }

    //扫描收货单
    public function Action_sanreceipt(){
        $this->title = '扫描收货单';

        $this->response->body(View::factory('receipt/sanreceipt'));
    }

    //处理收货页面提交过来的采购单号
    public function Action_check(){
        $this->title = '扫描收货';
        $warehouse_id = Kohana::$config->get('warehouse')->warehouse_id;
        $warehouse_location = Kohana::$config->get('warehouse')->warehouse_location;
        $batch_code = 0;
        $purchaseorder = 0;
        $view = View::factory('receipt/receipt');
        if(!empty($_GET['track_no'])){
            //供应商物流号
            $track_no = addslashes(trim($_GET['track_no'])); 
            $view->track_no = $track_no;
            $sql = "SELECT max(id),purchaseorder_id FROM purchaseorder_logistics WHERE track_no='$track_no'";
            $lt = DB::query(Database::SELECT,$sql)
                            ->execute('newerp')
                            ->current();
            if(!empty($lt['purchaseorder_id'])){
                $purchaseorder = $lt['purchaseorder_id'];
            }else{
                Message::error('供应商物流号对应采购单为空');
                $this->response->body($view);
                return false;
            }
            
        }else{
            Message::error('供应商物流号必须填写');
            $this->response->body($view);
            return false;
        }
        
        if(isset($_GET['batch_code'])){
            //批次号
            $batch_code = addslashes(trim($_GET['batch_code'])); 
            $view->batch_code = $batch_code;
        }
        if(isset($_GET['purchaseorder']) && $_GET['purchaseorder']){
            //采购单号
            $purchaseorder = addslashes(trim($_GET['purchaseorder'])); 
            $view->purchaseorder = $purchaseorder;
        }else{
            $view->purchaseorder = $purchaseorder;
        }

        $remark = '';
        if(!empty($purchaseorder) || !empty($batch_code)){
            $stores = Kohana::$config->load('vmi_warehouse')->as_array();
            if(!empty($purchaseorder)){
                $purchaseorders_status = comm::get_purchaseorders_status($purchaseorder);
                $view->purchaseordersearched = $purchaseorders_status;
                $purchase_id = $purchaseorders_status['purchase_id']; //采购员ID
                //判断采购单号是否存在采购单中
                if(!empty($purchaseorders_status)){
                    if(20 <= $purchaseorders_status['status'] && $purchaseorders_status['status'] < 50){
                        //查询采购明细表得到记录
                        $orms = comm::getPurchaseorderDetails($purchaseorder);
                        if(empty($orms)){
                            Message::error('你收到的产品已经取消了,或者是自动完结了，或者是完全入库了，或者是手动完结了！');
                            $this->response->body($view);
                        }
                        //添加采购订单备注
                        $sql = "select remark from purchaseorders where id=".$purchaseorder;
                        $remark_temp = DB::query(Database::SELECT,$sql)
                            ->execute('newerp')
                            ->current();
                        if(isset($remark_temp['remark'])){
                            $remark = $remark_temp['remark'];
                        }
                        $view->detail = $orms;
                        $view->planer = $purchaseorders_status['purchaseplaner']? 
                            comm::getNickByUserId($purchaseorders_status['purchaseplaner']):'';
                        
                        foreach($orms as $v){
                            $skuArr[] = $v['sku'];
                        }
                        if($skuArr){
                            $skuWares = Hznewerpclient::getWarehouses($skuArr);
                            if($skuWares){
                                $view->skuWares = $skuWares;
                            }
                        }
                    }else{
                        Message::error('你收到的产品已经取消了,或者是手动完结了，或者是完全入库了！');
                        //echo '<script>alert("你收到的产品没有在采购单中或者已经取消了！！");</script>';
                    }

                    $storeName = isset($stores[$purchaseorders_status['warehouseid']])
                        ? $stores[$purchaseorders_status['warehouseid']] : '未知仓库';
                    $print = comm::select_recieve_details($purchaseorder);
                    $view->purchase_id = Erpuser::nick_by_id($purchase_id);
                    $view->purchaseorder = $purchaseorder;
                    $view->storeId = $purchaseorders_status['warehouseid'];
                    $view->storeName = $storeName;
                    $view->print = $print;
                }else{
                    Message::error('你扫描的采购单号没有在采购系统中，可能没有打印或者已经在系统中被删除了！！');
                }
            }
            //批次号查询相关的采购单和收货明细单信息
            if(!empty($batch_code)){
                $sql = 'SELECT * FROM `batches` WHERE `batch_code`='.$batch_code;
                $sign = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
                if($sign){
                    $sql = "SELECT * FROM `recieve_details` WHERE `batch_code`=".$batch_code;
                    //收货明细
                    $recieve_details = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array('id');
                    if(empty($recieve_details)){
                        Message::error('当前批次号暂时没有收货明细！！');
                    }
                    $recieve_ids = array();
                    foreach($recieve_details as $recieve_detail_id => $details){
                        $recieve_ids[$recieve_detail_id] = $details['recieve_invoice_id'];
                    }
                    //查询采购单相关信息
                    $sql = 'SELECT * FROM `recieve_invoices` WHERE id IN ("'.implode('","',$recieve_ids).'")';
                    $recieve_invoices = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array('id');
                    $recieve_infos = array();
                    foreach($recieve_ids as $recieve_id => $recieve_info){
                        $sql = "SELECT `export_tax_rebate`
                            FROM `purchaseorders`
                            WHERE `id`=".$recieve_invoices[$recieve_ids[$recieve_id]]['purchaseorder_id'];
                        $export_tax_rebate = DB::query(Database::SELECT,$sql)->execute('newerp')->get('export_tax_rebate');
                        $recieve_infos[$recieve_id]['export_tax_rebate'] = $export_tax_rebate;
                        $recieve_infos[$recieve_id]['id'] = $recieve_id;
                        $recieve_infos[$recieve_id]['recieve_time'] = $recieve_invoices[$recieve_ids[$recieve_id]]['recieve_time'];
                        $recieve_infos[$recieve_id]['recieve_man'] = $recieve_invoices[$recieve_ids[$recieve_id]]['recieve_man'];
                        $recieve_infos[$recieve_id]['purchaseorder_id'] = $recieve_invoices[$recieve_ids[$recieve_id]]['purchaseorder_id'];
                        $purchaseorder_id = $recieve_infos[$recieve_id]['purchaseorder_id'];
                        $recieve_infos[$recieve_id]['purchase_man'] = Purchase::getPurchase_nameByPurchaseorder_id($purchaseorder_id);
                        $recieve_infos[$recieve_id]['sku'] = $recieve_details[$recieve_id]['sku'];
                        $recieve_infos[$recieve_id]['sku_name'] = $recieve_details[$recieve_id]['sku_name'];
                        $recieve_infos[$recieve_id]['storage_position'] = $recieve_details[$recieve_id]['storage_position'];
                        $recieve_infos[$recieve_id]['purchase_quantity'] = $recieve_details[$recieve_id]['purchase_quantity'];
                        $recieve_infos[$recieve_id]['arrival_quantity'] = $recieve_details[$recieve_id]['arrival_quantity'];
                        $recieve_infos[$recieve_id]['check_count'] = $recieve_details[$recieve_id]['check_count'];
                    }
                    $view->recieve_infos = $recieve_infos;
                }else{
                    Message::error('你扫描的批次号不存在！！');
                }
            }
            $this->response->body($view);
        }
        $view->remark = $remark;
        !isset($view->storeId) && $view->storeId = 0;
        !isset($view->storeName) && $view->storeName = '';
        $this->response->body($view);
    }

    public function Action_createbatch(){
        $this->title = '扫描收货';
        $t1 = date('Y-m-d 00:00:00');
        $t2 = date('Y-m-d 23:59:59');
        
        $sql = 'SELECT MAX(`batch_code`) AS `lastbatch`FROM `batches` WHERE `created` BETWEEN "'.$t1.'" AND "'.$t2.'"';
        $last_batch_code = DB::query(Database::SELECT,$sql)->execute('newerp')->get('lastbatch');

        $batch_code = 0;
        if($last_batch_code){
            $batch_code = $last_batch_code + 1;
        }else{
//            $warehouseid = Kohana::$config->get('warehouse')->warehouse_id;
            $day = date('Ymd');
            $batch_code = $day.'001';
        }
        try{
            $sql = 'INSERT INTO `batches` (`batch_code`,`created`,`userid`) 
                VALUES ('.$batch_code.',"'.date('Y-m-d H-i-s').'",'.User::active_user()->id.')';
            $rst_id = DB::query(Database::INSERT,$sql)->execute('newerp');

            Message::success('新建批次号成功！'.$batch_code);
            //include_once(dirname(dirname(dirname(dirname(__FILE__)))).'/common/logs.php');
            include_once(MODPATH.'/common/logs.php');
            logs::write_log($rst_id, 'batches insert', $rst_id);
        }catch (Exception $e){

        }

        $view = View::factory('receipt/receipt');
        $view->batch_code = $batch_code;
        $this->response->body($view);
    }

    //把采购记录添加到收货表和收货明细表
    public function Action_receiptinert(){
        $warehouse_id = Kohana::$config->get('warehouse')->warehouse_id;
        $warehouse_location = Kohana::$config->get('warehouse')->warehouse_location;
        $this->title = '收货界面';
        if(!empty($_POST['box_id']) && array_sum($_POST['arrival_quantity'])){
            //采购单
            $purchaseorder = trim($_POST['purchaseorder']);
            $purchaseorders_status = comm::get_purchaseorders_status($purchaseorder);
            $purchase_id = $purchaseorders_status['purchase_id']; //采购员ID
            //查询采购表
            $purchaseorder_insert = comm::get_purchaseorders_status($purchaseorder);
            $array = array();
            //$array['id'] = rand(-999999999,-1);
            $array['warehouseid'] = $purchaseorder_insert['warehouseid'];
            $array['purchaseorder_id'] = $purchaseorder_insert['id'];
            $array['recieve_time'] = date("Y-m-d H:i:s");
            $array['recieve_man'] = $this->user;
            $array['supplier'] = $purchaseorder_insert['supplier_id'];
            $array['store'] = $purchaseorder_insert['warehouseid'];
            $array['enterprise_dominant'] = $purchaseorder_insert['enterprise_dominant'];
            $array['track_no'] = $_POST['track_no'];
            //添加进收货表里
            $re = comm::insert_recieveinvoices('recieve_invoices',$array);
            //得到当前的收货单ID
            $str = $re[0];

            if(!empty($str)){
                $arr = array();
                foreach($_POST['box_id'] as $k => $v){
                    //采购明细表的ID
                    $arr[$k]['id'] = $v; 
                    $arr[$k]['sku'] = $_POST['sku'][$k];
                    $arr[$k]['sku_name'] = isset($_POST['sku_name'][$k])?stripslashes($_POST['sku_name'][$k]):'';
                    $place = skusystemapi::getSkuPlace($_POST['sku'][$k]);
                    if(isset($place[0]['place'])){
                        $arr[$k]['storage_position'] = $place[0]['place'];
                    }else{
                        $arr[$k]['storage_position'] = '';
                    }

                    $arr[$k]['sku_standard'] = isset($_POST['sku_standard'][$k])?stripslashes($_POST['sku_standard'][$k]):'';
                    $arr[$k]['quantity'] = trim($_POST['quantity'][$k]);
                    $arr[$k]['arrival_quantity'] = trim($_POST['arrival_quantity'][$k]);
                }
                $id = '';
                $sku = '';
                $sku_standard = '';
                $sku_name = '';
                $quantity = '';
                $storage_position = '';
                //到货数量
                $arrival_quantity = ''; 

                foreach($arr as $ke => $val){
                    $ss = '';
                    if($val['arrival_quantity'] == 0){
                        $ss = 1;
                        $status = 10;
                        $purchaseorder_status = 20;
                        continue;
                    }else{
                        if($val['quantity'] > $val['arrival_quantity'] && $val['arrival_quantity'] != 0){
                            $ss = 2;
                            $status = 20;
                            $purchaseorder_status = 40;
                        }elseif($val['quantity'] <= $val['arrival_quantity']){
                            $status = 30;
                            $purchaseorder_status = 50;
                        }

                        //添加进收货明细表
                        $arr_recievedetails = array();
                        //$arr_recievedetails['id'] = rand(-999999999,-1);
                        $arr_recievedetails['recieve_invoice_id'] = $str;
                        $arr_recievedetails['sku'] = $val['sku'];
                        $arr_recievedetails['sku_name'] = $val['sku_name'];
                        $arr_recievedetails['sku_standard'] = $val['sku_standard'];
                        $arr_recievedetails['storage_position'] = $val['storage_position'];
                        $arr_recievedetails['arrival_quantity'] = $val['arrival_quantity'];
                        $arr_recievedetails['purchase_quantity'] = $val['quantity']; //采购数量
                        $arr_recievedetails['warehouseid'] = $purchaseorder_insert['warehouseid'];
                        //设置sku质检核对状态（0：不许核对；10：待核对；20：已核对）
                        $sql = 'SELECT `id` FROM `skusystem_sku_qc_standard` WHERE `sku`="'.$val['sku'].'"';
                        $sign = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
                        $arr_recievedetails['skuchecksign'] = empty($sign) ? 0 : 10;

                        $recievedetails = comm::insert_recieveinvoices('recieve_details',$arr_recievedetails);
                        $ids = $recievedetails[0];
                        /*
                        $rdid = (int)((string)$ids.sprintf("%03d",$warehouse_id));
                        $sql = "UPDATE `recieve_details` SET `id` =".$rdid." WHERE `aid` =".$ids;
                        $dat = DB::query(Database::UPDATE,$sql);
                        $row = $dat->execute('newerp');
                        */
                        //查询SKU到货的次数
/*                         $count_sku = comm::sku_count($val['sku'],$purchaseorder);
                        if($count_sku<2){
                            //如果某个产品是第一次到货则更新采购明细表的状态
                            $update_purchaseorder_details = comm::update_status($val['sku'],$purchaseorder,$purchaseorder_status);
                        } */
                        
                        //更新采购明细的单的到货数量,收货表的ID $str 采购单ID $purchaseorder 采购明细ID $val['id']
                        $total_arrival_quantuty = comm::get_total_arrival_quantuty($purchaseorder,$val['sku']);
                        ($total_arrival_quantuty >= $val['quantity']) && $purchaseorder_status = 50;
                        $update_purchaseorder_details = comm::update_status($val['sku'],$purchaseorder,$purchaseorder_status);
                        $update_total_arrival_quantuty = comm::update_total_arrival_quantuty($val['sku'],$purchaseorder,$total_arrival_quantuty);

                        $id .= $ids.',';
                        $sku .= $val['sku'].',';
                        $sku_name .= $val['sku_name'].',';
                        $sku_standard .= $val['sku_standard'].',';
                        $storage_position .= $val['storage_position'].',';
                        $arrival_quantity .= $val['arrival_quantity'].',';
                        $quantity .= $val['quantity'].',';
                    }
                }
                
                $purchase_nick = Erpuser::nick_by_id($purchase_id);
                $url = url::base(TRUE).'printreceipt/skutiaoma?str='.$str.'&id='.$id.'&sku='.$sku.'&sku_name='.$sku_name.'&sku_standard='.$sku_standard.'&storage_position='.$storage_position.'&quantity='.$quantity.'&arrival_quantity='.$arrival_quantity.'&recieve_man='.$purchase_nick;

                $print = comm::select_recieve_details($purchaseorder);
                $stores = Kohana::$config->load('vmi_warehouse')->as_array();
                $storeName = isset($stores[$receieve_list['warehouseid']]) 
                    ? $stores[$purchaseorders_status['warehouseid']] : '未知仓库';

                $this->Action_check();
            }else{
                $this->Action_check();
            }
        }else{
            $this->Action_check();
        }
        include_once(MODPATH.'/common/logs.php');
        logs::purchaseorder_log($_POST['purchaseorder'],'收货：'.json_encode(array_combine($_POST['sku'],$_POST['arrival_quantity'])));//预约单日志
        logs::write_log();
    }

    //更新收货的数量
    public function action_receipt_update(){
        if(isset($_POST)){
            include_once(MODPATH.'/common/logs.php');
            $sku = trim($_POST['sku']);
            $id = trim($_POST['id']);
            $arrival_qty = trim($_POST['arrival_quantity']);
            $purchaseorder = trim($_POST['purchaseorder']);
            $print = comm::select_recieve_details($purchaseorder);
            //判断是否质检
            $check_count = comm::getCountOfCheck($id);
            if($check_count){
                echo '修改失败,该预约单已质检!!';
                logs::write_log($id, 'recieve_details update', 0);
            }else{
                $count_val = $_POST['count_val'];
                $flag_arrival = (comm::update_arrival_quantuty($id, $arrival_qty) === false) ? 0 : 1;
                
                logs::write_log($id, 'recieve_details update', $flag_arrival);
                if($flag_arrival){
                    $flag_detail = comm::update_arrival_quantity_to_purchaseorder_details(
                        $sku, $purchaseorder, $count_val) === false ? 0 : 1;
                    logs::write_log($purchaseorder, 'purchaseorder_details update', $flag_detail);
                }
                if($flag_arrival && $flag_detail){
                    echo '修改成功';
                } else {
                    echo '修改失败';
                }
            }
        }
    }

    //查找供应商
    public function action_select_supplier(){
        $name = $_GET['name'];
        $mark = array();
        $supplier = Newerpclientapi::getSupplierByName($name);

        count($supplier) && $mark = $supplier;
        echo json_encode($mark);
        exit;
    }

    //添加到页面批次
    public function action_addToBatchSingle(){
        if(!empty($_GET['batch_code']) && !empty($_GET['recieve_detail_id'])) {
            $sql = 'SELECT `id` FROM `check_quality_details` WHERE `recieve_detail_id`=' . $_GET['recieve_detail_id'];
            if(!DB::query(Database::SELECT,$sql)->execute('newerp')->get('id')) {
                $sql = 'SELECT `batch_code` FROM `recieve_details` WHERE `id` = '.$_GET['recieve_detail_id'];
                if(!DB::query(Database::SELECT,$sql)->execute('newerp')->get('batch_code')) {
                    $sql = 'UPDATE `recieve_details` SET `batch_code`='.$_GET['batch_code'].' WHERE `id`='.$_GET['recieve_detail_id'];
                    $rst = (DB::query(Database::UPDATE,$sql)->execute('newerp') === false) ? 0 : 1; 
                    $rst ? Message::success('添加成功！') : Message::error('添加失败！');
                    
                    //include_once(dirname(dirname(dirname(dirname(__FILE__)))).'/common/logs.php');
                    include_once(MODPATH.'/common/logs.php');
                    logs::write_log($_GET['recieve_detail_id'], 'recieve_details update', $rst);
                }else{
                    Message::error('当前收货明细已添加批次号！');
                }
            }else{
                Message::error('当前收货明细已质检，禁止添加批次号！');
            }
        }else{
            Message::error('批次号错误或收货明细ID不存在!');
        }

        $this->request->redirect("receipt/receiptinert?batch_code=" . $_GET['batch_code'] . '&purchaseorder=' . $_GET['purchaseorder'].'&track_no='.$_GET['track_no']);
    }

    public function action_addToBatchMore() {
        if(DB::select('id')
            ->from('batches')
            ->where('batch_code', '=', $_POST['batchCode'])
            ->execute('newerp')
            ->get('id')
        ) {
            $ids = join(',', $_POST['receiptDetailIds']);
            $sql = 'UPDATE `recieve_details` SET `batch_code`= ' . $_POST['batchCode'] . ' WHERE `id` IN ('. $ids .')';
            echo DB::query(Database::UPDATE,$sql)->execute('newerp');
            
            include_once(MODPATH.'/common/logs.php');
            logs::write_log($ids, 'recieve_details update');
            exit;
        }
        echo 0;
        exit;
    }

    public function action_getBatchCode() {
        $warehouse_id = Kohana::$config->get('warehouse')->warehouse_id;
        $results = array();
        if($warehouse_id && !empty($_GET['term'])){
            $sql = 'SELECT `batch_code`
                FROM `batches`
                WHERE `batch_code` LIKE \'' . $warehouse_id . '%' . $_GET['term'] . '\'
                ORDER BY `id` DESC
                LIMIT 5';

            $batch_codes = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array(NULL, 'batch_code');
            if(!empty($batch_codes)){
                foreach($batch_codes as $batch_code){
                    $results[] = array(
                        'label' => $batch_code,
                        'name' => $batch_code
                    );
                }
            }
        }

        echo json_encode($results);
        exit;
    }
}